/* eslint-disable prettier/prettier */
<template>
  <div>
    <el-card style="margin-bottom: 10px">
      <el-row :gutter="20">
        <el-col :span="2">
          <el-button type="danger" :icon="Back" style="font-size: 20px; padding: 0 6px" @click="turnBack()"></el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-row :gutter="10">
      <el-col :span="showMap ? 6 : 24">
        <el-card class="marker-list" body-style="padding: 0 10px" style="height: 100%">
          <template #header>
            <span>点位列表</span>
            <el-button type="primary" size="small" style="float: right" @click="OpenAddMarkerDialog">添加点位</el-button>
            <el-button size="small" style="float: right; margin-right: 10px" @click="showMapOrNot">{{
              showMap ? "收起地图" : "展开地图"
            }}</el-button>
            <el-button size="small" style="float: right" @click="clearFilter">重置列表</el-button>
          </template>
          <!--筛选用的tag列表-->
          <el-table ref="tableRef" class="custom-table" border :data="detailData" height="95%">
            <el-table-column prop="mapDetailDesc" label="点位名称"></el-table-column>
            <el-table-column
              prop="unitName"
              label="机组"
              :filters="units"
              :filter-method="filterUnit"
              filter-placement="bottom-end"
            >
            </el-table-column>
            <el-table-column prop="nfcName" label="点位编码"></el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button type="warning" size="small" @click="OpenEditMarkerDialog(scope.row)" text style="padding: 0 0">
                  修改
                </el-button>
                <el-button type="danger" @click="deleteMarker(scope.row)" size="small" text style="padding: 0 0">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card id="map-container" v-show="showMap"> </el-card>
        <div id="panel" v-show="showMap"></div>
      </el-col>
    </el-row>
    <el-dialog title="添加点位" v-model="showAddMarkerDialog" width="500px">
      <!-- 表单 -->
      <el-form label-width="120px">
        <el-form-item label="选择点位">
          <el-select v-model="selectedMapPointId">
            <el-option
              v-for="point in OptionalPoints"
              :key="point.mapDetailId"
              :value="point.mapDetailId"
              :label="point.mapDetailDesc"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 对话框底部按钮 -->
      <template #footer>
        <el-button @click="showAddMarkerDialog = false">取消</el-button>
        <el-button type="primary" @click="ConfirmAddMarker">提交</el-button>
      </template>
    </el-dialog>

    <el-dialog title="修改点位信息" v-model="showEditMarkerDialog" width="500px">
      <!-- 表单 -->
      <el-form :model="editForm" ref="editFormRef" label-width="120px" :rules="addRules">
        <el-form-item label="点位名称" prop="mapDetailDesc">
          <el-input v-model="editForm.mapDetailDesc"></el-input>
        </el-form-item>
        <el-form-item label="机组" prop="unitId">
          <el-select v-model="editForm.unitId" placeholder="选择机组" clearable>
            <el-option v-for="unit in unitArray" :key="unit.unitId" :label="unit.unitName" :value="unit.unitId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="NFC" prop="mapNfcMsg">
          <el-select v-model="editForm.mapNfcMsg" placeholder="选择编码信息" clearable>
            <el-option v-for="nfc in NfcArray" :key="nfc.nfcName" :label="nfc.nfcName" :value="nfc.nfcMsg"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 对话框底部按钮 -->
      <template #footer>
        <el-button @click="showEditMarkerDialog = false">取消</el-button>
        <el-button type="primary" @click="ConfirmEditMarker">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="js">
import { onMounted, onUnmounted, reactive, ref, watch } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { Back } from "@element-plus/icons-vue";
import request from "@/api/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
import iconImage1 from "@/assets/icons/locationpng.png";

let map = null;
let icon = null;
const showAddMarkerDialog = ref(false);
const showEditMarkerDialog = ref(false);
const selectedMapPointId = ref();
const addForm = ref({});
const editForm = reactive({});
const editFormRef = ref(null);
const addRules = {
  mapDetailDesc: [{ required: true, message: "请输入点位名称", trigger: "blur" }],
  mapLongitude: [{ required: true, message: "请输入经度", trigger: "blur" }],
  mapLatitude: [{ required: true, message: "请输入纬度", trigger: "blur" }],
  unitId: [{ required: true, message: "请输入机组Id", trigger: "blur" }],
  mapNfcMsg: [{ required: true, message: "请选编码信息", trigger: "blur" }]
};

const unitArray = ref([]);
const NfcArray = ref([]);
const showMap = ref(false);

let clickPoint = [];

const detailData = ref([]);
let markers = [];

const OptionalPoints = ref([]);

const props = defineProps({
  mapDetails: {
    type: Array,
    required: false
  },
  mapInfo: {
    type: Object,
    required: true
  }
});

const units = ref([
  { text: "Home", value: "Home" },
  { text: "Office", value: "Office" }
]);

const make_unit_filter = () => {
  unitArray.value.forEach(item => {
    units.value.push({
      text: item.unitName,
      value: item.unitName
    });
  });
};

const getAllNFCs = () => {
  request.get("/api-self/NFC").then(res => {
    const data = res.data;
    if (data.code === 0) {
      NfcArray.value = data.data;
    } else {
      ElMessage.error("获取编码数据失败：" + data.message);
    }
  });
};
const getAllUnits = () => {
  request.get("/api-self/users/unit/getUnits").then(res => {
    const data = res.data;
    if (data.code === 0) {
      unitArray.value = data.data;
      make_unit_filter();
    } else {
      ElMessage.error("获取机组数据失败：" + data.message);
    }
  });
};
const tableRef = ref();
//过滤器
const filterUnit = (value, row) => {
  return row.unitName === value;
};
const clearFilter = () => {
  if (tableRef.value) {
    tableRef.value.clearFilter();
  }
};
// 监听 props.mapDetails 的变化
watch(
  () => props.mapDetails, // 监听目标
  newMapDetails => {
    // 变化时的回调函数
    if (newMapDetails) {
      // 将 props.mapDetails 浅拷贝到 detailData
      detailData.value = [...newMapDetails]; // 使用扩展运算符进行浅拷贝
    }
  },
  { immediate: true } // 如果希望初始化时也触发一次监听，可以加上这个选项
);
onMounted(() => {
  getAllNFCs();
  getAllUnits();
  if (props.mapDetails) {
    detailData.value = props.mapDetails;
  }
  getAllPoints();
  window._AMapSecurityConfig = {
    securityJsCode: "701b2c8adf1951bafc116e4a916cf996"
  };
  AMapLoader.load({
    key: "dd93fce2d1e6b0eb1d3e438c7a2581c0", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: [
      "AMap.Scale",
      "AMap.ControlBar",
      "AMap.MapType",
      "AMap.ToolBar",
      "AMap.Marker",
      "AMap.PlaceSearch",
      "AMap.Geolocation"
    ] //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then(AMap => {
      map = new AMap.Map("map-container", {
        // 设置地图容器id
        viewMode: "2D", // 是否为3D地图模式
        zoom: 11 // 初始化地图级别
      });

      const placeSearch = new AMap.PlaceSearch({
        pageSize: 5, // 单页显示结果条数
        pageIndex: 1, // 页码
        map: map, // 展现结果的地图实例
        panel: "panel", // 结果列表将在此容器中进行展示。
        autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
      });

      icon = new AMap.Icon({
        size: new AMap.Size(30, 40), //图标尺寸
        image: iconImage1, //Icon 的图像
        imageOffset: new AMap.Pixel(-2, 0), //图像相对展示区域的偏移量，适于雪碧图等
        imageSize: new AMap.Size(40, 40) //根据所设置的大小拉伸或压缩图片
      });

      const marker = new AMap.Marker({
        offset: [0, 6],
        zIndex: 99
      });
      map.add(marker);

      map.on("click", function (e) {
        clickPoint = [e.lnglat.getLng(), e.lnglat.getLat()];
        // const distance = AMap.GeometryUtil.distance(yourPosition, clickPoint);

        // 自定义点标记内容
        const markerContent = document.createElement("div");
        // 点标记中的图标
        const markerImg = document.createElement("img");
        markerImg.className = "markerlnglat";
        markerImg.src = "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png";
        markerImg.setAttribute("width", "25px");
        markerImg.setAttribute("height", "34px");
        markerContent.appendChild(markerImg);

        // const markerSpan = document.createElement("div");
        // markerSpan.className = "marker";
        // markerSpan.style =
        //   "position: absolute;\n" +
        //   "  top: -32px;\n" +
        //   "  left: 20px;\n" +
        //   "  padding: 4px 10px;\n" +
        //   "  font-size: 12px;\n" +
        //   "  color: #ffffff;\n" +
        //   "  white-space: nowrap;\n" +
        //   "  background-color: #25a5f7;\n" +
        //   "  border-radius: 3px;\n" +
        //   "  box-shadow: 1px 1px 1px rgb(10 10 10 / 20%);";
        // markerSpan.innerHTML = "距离您" + Math.round(distance) + "米";
        // markerContent.appendChild(markerSpan);

        marker.setContent(markerContent);
        marker.setPosition(clickPoint);
      });

      const controlBar = new AMap.ControlBar();
      map.addControl(controlBar);

      const scale = new AMap.Scale();
      map.addControl(scale);

      const toolBar = new AMap.ToolBar();
      map.addControl(toolBar);

      // 在地图时启用定位
      // 初始化 Geolocation 插件
      // const geolocation = new AMap.Geolocation({
      //   enableHighAccuracy: true, // 是否使用高精度定位，默认：true
      //   timeout: 10000, // 设置定位超时时间，默认：无穷大
      //   offset: [20, 90], // 定位按钮的停靠位置的偏移量
      //   zoomToAccuracy: true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      //   position: "RB" // 定位按钮的排放位置,  RB表示右下
      // });

      // map.addControl(geolocation);

      // geolocation.getCurrentPosition((status, result) => {
      //   if (status === "complete") {
      //     onComplete(result);
      //   } else {
      //     onError(result);
      //   }
      // });
      onComplete();
      // 调整地图视野以包含所有标记
      map.setFitView(markers);

      function onComplete() {
        // data是具体的定位信息
        // const position = data.position;
        // map.setCenter(position); // 将地图中心点设置为定位点
        // longitude.value = position.lng;
        // latitude.value = position.lat;
        // yourPosition = [position.lng, position.lat];
        // console.log("定位成功", yourPosition);
        if (props.mapDetails) {
          props.mapDetails.forEach(detail => {
            const point = [detail.mapLongitude, detail.mapLatitude];
            const label = { content: detail.mapDetailDesc, offset: [10, -10] };
            // const distance = AMap.GeometryUtil.distance(yourPosition, point);
            // const content = "距离您" + Math.round(distance) + "米";
            const detailMarker = new AMap.Marker({
              icon: icon,
              clickable: false,
              label: label,
              // title: content,
              position: point,
              extData: detail,
              offset: [-18, -40],
              map: map
            });
            markers.push(detailMarker);
          });
        }
      }
      // function onError(data) {
      //   // 定位出错
      //   console.error("定位失败", data);
      // }

      // geolocation.getCityInfo((status, result) => {
      //   if (status === "complete") {
      //     city = result.city;
      //     placeSearch = new AMap.PlaceSearch({
      //       city: city,
      //       pageSize: 5, // 单页显示结果条数
      //       pageIndex: 1, // 页码
      //       map: map, // 展现结果的地图实例
      //       panel: "panel", // 结果列表将在此容器中进行展示。
      //       autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
      //     });
      //   } else {
      //     onError(result);
      //   }
      // });

      // 其他插件初始化和地图相关的代码
      map.plugin(["AMap.AutoComplete"], function () {
        const autoOptions = {
          //使用联想输入的 input 的 id
          input: "searchInput"
        };
        const autocomplete = new AMap.AutoComplete(autoOptions);
        autocomplete.on("select", function (e) {
          //针对选中的poi实现自己的功能
          placeSearch.search(e.poi.name);
        });
      });
    })
    .catch(e => {
      console.log(e);
    });
});
const emit = defineEmits(["turnBack", "refreshData"]);
const turnBack = () => {
  emit("turnBack");
};

const deleteMarker = row => {
  console.log("delete:" + row.mapDetailId);
  if (markers.length <= 1) {
    ElMessage.warning("至少保留一个点位");
    return;
  }
  ElMessageBox.confirm("将会删除这个点位，确定吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    request.delete("/api-self/inspection/map/detail/" + row.mapDetailId).then(res => {
      const data = res.data;
      if (data.code === 0) {
        removeDetailById(row.mapDetailId);
        ElMessage.success("删除成功");
      } else {
        ElMessage.error("删除失败：" + data.message);
      }
    });
  });
};
const removeDetailById = id => {
  let index = detailData.value.findIndex(detail => detail.mapDetailId === id);
  if (index !== -1) {
    detailData.value.splice(index, 1);
  }
  index = markers.findIndex(marker => marker.getExtData().mapDetailId === id);
  if (index !== -1) {
    markers[index].setMap(null);
    markers.splice(index, 1);
  }
};
const OpenAddMarkerDialog = () => {
  showAddMarkerDialog.value = true;
  selectedMapPointId.value = null;
};
const ConfirmAddMarker = () => {
  if (selectedMapPointId.value == null) {
    ElMessage.warning("请选择点位");
    return;
  }
  addForm.value = OptionalPoints.value.find(point => point.mapDetailId === selectedMapPointId.value);
  addForm.value.mapId = props.mapInfo.mapId;
  console.log("ADD", addForm.value);
  request.post("/api-self/inspection/map/mapDetail", addForm.value).then(res => {
    const data = res.data;
    if (data.code === 0) {
      addNewMarkerToMap();
      ElMessage.success("添加成功");
      emit("refreshData");
      showAddMarkerDialog.value = false;
    } else {
      ElMessage.error("添加失败：" + data.message);
    }
  });
};
const OpenEditMarkerDialog = row => {
  showEditMarkerDialog.value = true;
  editForm.mapDetailDesc = row.mapDetailDesc;
  editForm.mapDetailId = row.mapDetailId;
  editForm.mapId = props.mapInfo.mapId;
  editForm.mapNfcMsg = row.mapNfcMsg;
  editForm.unitId = row.unitId;
};
const ConfirmEditMarker = () => {
  editFormRef.value.validate(valid => {
    if (valid) {
      console.log("Edit", editForm);
      request.put("/api-self/inspection/map/detail", editForm).then(res => {
        const data = res.data;
        if (data.code === 0) {
          markers
            .find(marker => marker.getExtData().mapDetailId === editForm.mapDetailId)
            .setLabel({ content: editForm.mapDetailDesc, offset: [10, -10] });
          ElMessage.success("修改成功");
          emit("refreshData");
        } else {
          ElMessage.error("修改失败：" + data.message);
        }
      });
    }
  });
};
const addNewMarkerToMap = () => {
  const point = [addForm.value.mapLongitude, addForm.value.mapLatitude];
  const label = { content: addForm.value.mapDetailDesc, offset: [10, -10] };
  // const distance = AMap.GeometryUtil.distance(yourPosition, point);
  // const content = "距离您" + Math.round(distance) + "米";
  const newMarker = new AMap.Marker({
    icon: icon,
    clickable: false,
    label: label,
    // title: content,
    position: point,
    extData: addForm,
    offset: [-18, -40]
  });
  map.add(newMarker);
  markers.push(newMarker);
};
const getAllPoints = () => {
  request.get("/api-self/inspection/map/1").then(res => {
    const data = res.data;
    if (data.code === 0) {
      OptionalPoints.value = data.data;
    } else {
      ElMessage.error("获取可选点位信息失败：" + data.message);
    }
  });
};
onUnmounted(() => {
  console.log("unmounted");
  map.clearMap();
  map?.destroy();
});

const showMapOrNot = () => {
  showMap.value = !showMap.value;
};

//tag 相关
</script>

<style scoped>
#map-container {
  width: 100%;
  height: 74vh;
}
.marker-list {
  width: 100%;
  height: 74vh;
}
#panel {
  position: fixed;
  top: 200px;
  right: 20px;
  width: 300px;
  max-height: 90%;
  overflow-y: auto;
  background-color: white;
  border-bottom: solid 0 silver;
}
.custom-table :deep(.el-table__header-wrapper thead tr th) {
  color: #000000;
  text-align: center;
  background-color: #fafafa;
}
.custom-table :deep(.el-table__body-wrapper tbody tr td) {
  text-align: center; /* 单元格内容居中 */
}
</style>
